# coding=utf-8
import time
import json
import redis
from playwright.sync_api import sync_playwright


redis_con = redis.Redis(host='121.4.69.146', password='xhhg123456',
                        port=6389, db=2, decode_responses=True)     # 连接redis数据库


def run(i, inst, port):
    with sync_playwright() as p:
        storage_state_path = f'./auth/{inst}_state.json'
        with open(storage_state_path) as file:
            storage_state = json.load(file)
            origins = storage_state.get('origins')
            local_stroge_list = [item.get('localStorage') for item in origins]
            for local_stroge in local_stroge_list:
                for item in local_stroge:
                    if item.get('name') == 'ACCESS_TOKEN':
                        authorization = item.get('value')
        print(f'成功读取{inst}登录信息:{authorization}')
        browser = p.firefox.launch()
        context = browser.new_context(
            base_url='https://cpquery.cponline.cnipa.gov.cn', storage_state=storage_state_path, ignore_https_errors=True)
        context.set_default_timeout(600000)
        context.set_default_navigation_timeout(600000)
        page = context.new_page()
        page.set_default_timeout(600000)
        page.set_default_navigation_timeout(600000)
        page.goto(
            'https://cpquery.cponline.cnipa.gov.cn/chinesepatent/index')
        page.wait_for_load_state('networkidle')
        while redis_con.scard(port):
            sqh = redis_con.spop(port).replace("ZL", '')
            start_time = time.time()
            print(f'@@开始查询申请号:{sqh}_专利状态信息@@')
            api_request_context = context.request
            headers = {
                "Accept": "application/json, text/plain, */*",
                "Content-Type": "application/json;charset=utf-8",
                "Authorization": 'Bearer ' + authorization,
                "userType": "USER_RZ_DAILIJIG"
            }
            sqxx_response = api_request_context.post(
                '/api/view/gn/sqxx', data={'zhuanlisqh': sqh}, headers=headers, timeout=0)
            patent_status_res_json = sqxx_response.json()
            print(patent_status_res_json)
            end_time = time.time()
            print(f"{sqh}_本次耗时: {end_time-start_time}")
            print('---' * 10)
            page.reload()


if __name__ == '__main__':
    port_dict = {'XHHG': '信合红谷接口查询', 'XH': '协和端口查询', 'WB': "外部接口查询"}
    inst = 'XHHG'
    port = port_dict.get(inst)
    run(0, inst, port)
